<script setup>
import { reactive, useTemplateRef } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import SelectDealer from './SelectDealer.vue'
import { handleLogger } from '@renderer/util/common'

const show = defineModel('show', { type: Boolean, default: false })
const emits = defineEmits(['success'])

function disabledDate(date) {
  return dayjs(date).isAfter(dayjs())
}

// 正则表达式：允许负数和最多两位小数
const validateNumber = (rule, value, callback) => {
  const regex = /^-?\d*(\.\d{0,2})?$/
  if (!value) {
    callback(new Error('请输入数字'))
  } else if (!regex.test(value)) {
    callback(new Error('只能输入数字，最多两位小数'))
  } else {
    callback()
  }
}
const formRules = {
  dealerId: [{ required: true, message: '请选择经销商名称', trigger: 'blur' }],
  date: [{ required: true, message: '请选择业绩日期', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入业绩金额', trigger: 'blur' },
    {
      validate: validateNumber,
      message: '请输入数字，最多两位小数',
      trigger: 'blur'
    }
  ]
}
const formState = reactive({
  dealerParentId:0,
  dealerParentName:'',
  dealerId: '',
  dealerName: '',
  dealerLevelId: '',
  dealerLevelName: '',
  dealerRemark: '',
  date: '',
  price: ''
})
function validatePriceInput(value) {
  const validValue = value.match(/^-?\d*(\.\d{0,2})?$/) ? value : formState.price
  formState.price = validValue
}
const formRef = useTemplateRef('formRef')
async function handleConfirm() {
  await formRef.value.validate()
  const res = await window.api.insertPerformance(
    formState.dealerId,
    formState.dealerName,
    formState.dealerParentId,
    formState.dealerParentName,
    formState.dealerLevelId,
    formState.dealerLevelName,
    formState.date,
    Number(formState.price)
  )
  if (res > 0) {
    ElMessage.success('录入成功')
    handleLogger(`业绩录入：${formState.dealerName}${formState.date}业绩金额${formState.price}`)
    emits('success')
    formState.dealerId = ''
    formState.dealerName = ''
    formState.dealerLevelId = ''
    formState.dealerLevelName = ''
    formState.dealerRemark = ''
    formState.date = ''
    formState.price = ''
    formState.dealerParentId=0
    formState.dealerParentName=''
    show.value = false
  }
}

function handleDealerChange(e) {
  formState.dealerLevelId = e.dealer_level_id
  formState.dealerLevelName = e.dealer_level_name
  formState.dealerName = e.dealer_name
  formState.dealerRemark = e.dealer_remark
  formState.dealerParentId=e.parent_dealer_id
  formState.dealerParentName=e.parent_dealer_name
}
</script>

<template>
  <el-dialog v-model="show" width="600" title="录入业绩" draggable>
    <el-form ref="formRef" :model="formState" :rules="formRules" label-width="100px">
      <el-form-item label="经销商等级">
        <span>{{ formState.dealerLevelName }}</span>
      </el-form-item>
      <el-form-item label="经销商名称" prop="dealerId">
        <SelectDealer
          v-model:dealerid="formState.dealerId"
          style="width: 400px"
          @change="handleDealerChange"
        />
      </el-form-item>
      <el-form-item label="业绩日期" prop="date">
        <el-date-picker
          v-model="formState.date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="业绩日期"
          style="width: 400px"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item label="业绩金额" prop="price">
        <el-input
          v-model.number="formState.price"
          type="number"
          placeholder="业绩金额"
          style="width: 400px; margin-right: 10px"
          @input="validatePriceInput"
        />
        <span>元</span>
      </el-form-item>
      <el-form-item label="备注">
        <span>{{ formState.dealerRemark }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
